<template>
    <div class="enterprise-fee-management">
        <!-- 统计卡片区域 -->
        <el-row :gutter="20" class="stats-card-row mb-4">
            <el-col :span="6">
                <el-card class="stats-card" style="background: linear-gradient(135deg, #fef9f2 0%, #fde6c8 100%);">
                    <div class="stats-card-content">
                        <p class="stats-card-label">
                            <span v-if="yearTotal">
                                {{ yearTotal }}年
                            </span>
                            总应缴金额
                        </p>
                        <p class="stats-card-value">{{ formatCurrency(myTotalPayable) }}</p>
                        <p class="stats-card-desc">
                            <span class="text-primary">
                                <i class="el-icon-info"></i> 包含所有费用项
                            </span>
                        </p>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card" style="background: linear-gradient(135deg, #f2f9f5 0%, #c8f0de 100%);">
                    <div class="stats-card-content">
                        <p class="stats-card-label">
                            <span v-if="yearTotal">
                                {{ yearTotal }}年
                            </span>
                            总已缴金额
                        </p>
                        <p class="stats-card-value">{{ formatCurrency(myTotalPaid) }}</p>
                        <p class="stats-card-desc">
                            <span class="text-success">
                                <i class="el-icon-check"></i> 已完成支付
                            </span>
                        </p>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card" style="background: linear-gradient(135deg, #f9f2f2 0%, #f0c8c8 100%);">
                    <div class="stats-card-content">
                        <p class="stats-card-label">
                            <span v-if="yearTotal">
                                {{ yearTotal }}年
                            </span>总欠缴金额
                        </p>
                        <p class="stats-card-value">{{ formatCurrency(totalArrears) }}</p>
                        <p class="stats-card-desc">
                            <span class="text-warning">
                                <i class="el-icon-exclamation"></i> 需要催收
                            </span>
                        </p>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card class="stats-card" style="background: linear-gradient(135deg, #f2f5f9 0%, #c8d4f0 100%);">
                    <div class="stats-card-content">
                        <p class="stats-card-label">
                            <span v-if="yearTotal">
                                {{ yearTotal }}年
                            </span>
                            政策减免总额
                        </p>
                        <p class="stats-card-value">{{ formatCurrency(totalPolicyReduction) }}</p>
                        <p class="stats-card-desc">
                            <span class="text-info">
                                <i class="el-icon-discount"></i> 政策优惠
                            </span>
                        </p>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 费用列表 -->
        <!-- 搜索和操作区域 -->
        <el-card class="mb-4">
            <el-form inline :model="searchForm" class="search-form">
                <el-form-item label="选择企业">
                    <el-select v-model="searchForm.enterpriseId" placeholder="选择企业" clearable filterable
                        @change="handleEnterpriseId">
                        <el-option v-for="enterprise in enterprises" :key="enterprise.id" :label="enterprise.name"
                            :value="enterprise.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择年份">
                    <el-select v-model="searchForm.feeYear" placeholder="选择年份" clearable style="width: 150px"
                        @change="handleYear">
                        <el-option v-for="year in searchYears" :key="year" :label="year + '年'" :value="year" />
                    </el-select>
                </el-form-item>

                <el-form-item label="欠缴状态">
                    <el-select v-model="searchForm.arrearsStatus" placeholder="欠缴状态" clearable style="width: 150px"
                        @change="handleArrearsStatus">
                        <el-option label="全部" value="" />
                        <el-option label="有欠缴" value="1" />
                        <el-option label="无欠缴" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleSearch">
                        <i class="el-icon-refresh"></i> 查询
                    </el-button>
                    <el-button @click="handleReset">
                        <i class="el-icon-refresh"></i> 重置
                    </el-button>
                    <el-button type="primary" @click="handleAdd">
                        <i class="el-icon-plus"></i> 新增费用记录
                    </el-button>
                    <el-button type="success" @click="openExportDialog" class="export-btn">
                        <el-icon>
                            <Download />
                        </el-icon>
                        导出数据
                    </el-button>
                </el-form-item>
            </el-form>

            <el-table :data="feeList" :border="true" stripe :loading="tableLoading" @row-click="handleRowClick"
                row-key="feeId">
                <el-table-column prop="enterprise.enterpriseName" label="企业名称" :align="'center'" />
                <el-table-column prop="feeYear" label="费用年份" sortable :align="'center'" />
                <el-table-column prop="totalPayable" label="应缴合计" :align="'center'"
                    :formatter="(row, column, cellValue) => formatCurrency(cellValue)" sortable />
                <el-table-column prop="totalPaid" label="已缴合计" :align="'center'"
                    :formatter="(row, column, cellValue) => formatCurrency(cellValue)" sortable />
                <el-table-column prop="currentYearArrears" label="本年度欠缴" :align="'center'"
                    :formatter="(row, column, cellValue) => formatCurrency(cellValue)" sortable
                    :cell-style="({ row }) => row.currentYearArrears > 0 ? { color: '#E6A23C' } : {}" />
                <el-table-column prop="policyReduction" label="政策减免" :align="'center'"
                    :formatter="(row, column, cellValue) => formatCurrency(cellValue)" />
                <el-table-column prop="updatedAt" label="最近更新" :align="'center'" sortable />
                <el-table-column label="操作" width="220" :align="'center'" fixed="right">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleViewDetail(scope.row)">
                            查看详情
                        </el-button>
                        <el-button size="small" type="warning" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" text-color="#F56C6C" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
                :current-page="pagination.currentPage" :page-sizes="[10, 20, 50]" :page-size="pagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />

        </el-card>
        <!-- 详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="费用详情" :width="detailDialogWidth" :fullscreen="isMobile">
            <el-row :gutter="20">
                <el-col :span="24" class="mb-4">
                    <el-descriptions column="1" :border="true">
                        <el-descriptions-item label="企业名称">{{ currentFee.enterprise.enterpriseName
                            }}</el-descriptions-item>
                        <el-descriptions-item label="费用年份">{{ currentFee.feeYear }}年</el-descriptions-item>
                        <el-descriptions-item label="最近更新">{{ currentFee.updatedAt }}</el-descriptions-item>
                        <el-descriptions-item label="备注">{{ currentFee.remark || '-' }}</el-descriptions-item>
                    </el-descriptions>
                </el-col>

                <el-col :span="12">
                    <el-card>
                        <div slot="header">单价信息</div>
                        <el-descriptions column="1" :border="true">
                            <el-descriptions-item label="管理费单价（元/平方米）">{{ formatCurrency(currentFee.managementFeeUnit)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="物管费单价（元/平方米）">{{ formatCurrency(currentFee.propertyFeeUnit)
                            }}</el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-col>

                <el-col :span="12">
                    <el-card>
                        <div slot="header">应缴费用</div>
                        <el-descriptions column="1" :border="true">
                            <el-descriptions-item label="应缴管理费">{{ formatCurrency(currentFee.payableManagementFee)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="应缴履约保证金">{{ formatCurrency(currentFee.payablePerformanceBond)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="应缴物管费">{{ formatCurrency(currentFee.payablePropertyFee)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="应缴水电费">{{ formatCurrency(currentFee.payableWaterElectricity)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="政策减免">{{ formatCurrency(currentFee.policyReduction)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="应缴合计" label-class-name="font-bold"
                                content-class-name="font-bold text-primary">{{ formatCurrency(currentFee.totalPayable)
                                }}</el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-col>

                <el-col :span="12">
                    <el-card>
                        <div slot="header">已缴费用</div>
                        <el-descriptions column="1" :border="true">
                            <el-descriptions-item label="已缴管理费">{{ formatCurrency(currentFee.paidManagementFee)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="已缴履约保证金">{{ formatCurrency(currentFee.paidPerformanceBond)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="已缴物管费">{{ formatCurrency(currentFee.paidPropertyFee)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="已缴水电费">{{ formatCurrency(currentFee.paidWaterElectricity)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="已缴合计" label-class-name="font-bold"
                                content-class-name="font-bold text-success">{{ formatCurrency(currentFee.totalPaid)
                                }}</el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-col>

                <el-col :span="12">
                    <el-card>
                        <div slot="header">欠缴费用</div>
                        <el-descriptions column="1" :border="true">
                            <el-descriptions-item label="欠缴管理费">{{ formatCurrency(currentFee.arrearsManagementFee)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="欠缴履约保证金">{{ formatCurrency(currentFee.arrearsPerformanceBond)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="欠缴物管费">{{ formatCurrency(currentFee.arrearsPropertyFee)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="欠缴水电费">{{ formatCurrency(currentFee.arrearsWaterElectricity)
                            }}</el-descriptions-item>
                            <el-descriptions-item label="本年度欠缴" label-class-name="font-bold"
                                content-class-name="font-bold text-warning">{{
                                    formatCurrency(currentFee.currentYearArrears)
                                }}</el-descriptions-item>
                        </el-descriptions>
                    </el-card>
                </el-col>
            </el-row>
            <template #footer>
                <el-button @click="detailDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 表单对话框（新增/编辑） -->
        <el-dialog v-model="formDialogVisible" :title="isEditMode ? '编辑费用记录' : '新增费用记录'" :width="formDialogWidth"
            :draggable="true" :fullscreen="isMobile">
            <el-form ref="feeFormRef" :model="feeForm" :rules="formRules" label-width="155px" class="fee-form">
                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="企业" prop="enterpriseId">
                            <!-- 用 div 包裹 select 和 tooltip，实现横向布局 -->
                            <div class="select-with-tooltip">
                                <el-select v-model="feeForm.enterpriseId" placeholder="请选择企业" :disabled="isEditMode"
                                    filterable clearable @change="handleEnterPriseChange"
                                    @clear="handleEnterPriseClear">
                                    <el-option v-for="enterprise in enterprises" :key="enterprise.id"
                                        :label="enterprise.name" :value="enterprise.id" />
                                </el-select>

                                <!-- 提示图标和 tooltip -->
                                <el-tooltip effect="light" placement="top" :content="enterpriseTooltip" raw-content>
                                    <el-icon class="info-icon">
                                        <InfoFilled />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="费用年份" prop="feeYear">
                            <el-select v-model="feeForm.feeYear" placeholder="请选择费用年份" :disabled="isEditMode">
                                <el-option v-for="year in availableYears" :key="year" :label="year + '年'"
                                    :value="year" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-divider content-position="left">单价信息</el-divider>
                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="管理费单价（元/㎡）" prop="managementFeeUnit">
                            <el-input v-model.number="feeForm.managementFeeUnit" placeholder="请输入管理费单价" suffix="元/平方米"
                                type="number" @input="handleInputManagementFeeUnit" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="物管费单价（元/㎡）" prop="propertyFeeUnit">
                            <el-input v-model.number="feeForm.propertyFeeUnit" placeholder="请输入物管费单价" suffix="元/平方米"
                                type="number" @input="handleInputPropertyFeeUnit" />
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-divider content-position="left">应缴费用</el-divider>
                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="应缴管理费" prop="payableManagementFee">
                            <el-input v-model.number="feeForm.payableManagementFee" placeholder="请输入应缴管理费" suffix="元"
                                type="number" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应缴履约保证金" prop="payablePerformanceBond">
                            <el-input v-model.number="feeForm.payablePerformanceBond" placeholder="请输入应缴履约保证金"
                                type="number" suffix="元" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="应缴物管费" prop="payablePropertyFee">
                            <el-input v-model.number="feeForm.payablePropertyFee" placeholder="请输入应缴物管费" suffix="元"
                                type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应缴水电费" prop="payableWaterElectricity">
                            <el-input v-model.number="feeForm.payableWaterElectricity" placeholder="请输入应缴水电费"
                                type="number" suffix="元" />
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="政策减免（元/年）" prop="policyReduction">
                            <el-input v-model.number="feeForm.policyReduction" placeholder="请输入政策减免金额" suffix="元"
                                type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="应缴合计" prop="totalPayable">
                            <el-input v-model.number="feeForm.totalPayable" placeholder="应缴合计金额" suffix="元" readonly
                                :style="{ backgroundColor: '#f5f7fa' }" type="number" />
                            <el-button type="text" @click="calculateTotalPayable" size="small">
                                自动计算
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-divider content-position="left">已缴费用</el-divider>

                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="已缴管理费" prop="paidManagementFee">
                            <el-input v-model.number="feeForm.paidManagementFee" placeholder="请输入已缴管理费" suffix="元"
                                type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="已缴履约保证金" prop="paidPerformanceBond">
                            <el-input v-model.number="feeForm.paidPerformanceBond" placeholder="请输入已缴履约保证金"
                                type="number" suffix="元" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :span="20">
                    <el-col :span="12">
                        <el-form-item label="已缴物管费" prop="paidPropertyFee">
                            <el-input v-model.number="feeForm.paidPropertyFee" placeholder="请输入已缴物管费" suffix="元"
                                type="number" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="已缴水电费" prop="paidWaterElectricity">
                            <el-input v-model.number="feeForm.paidWaterElectricity" placeholder="请输入已缴水电费" suffix="元"
                                type="number" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="已缴合计" prop="totalPaid">
                    <el-input v-model.number="feeForm.totalPaid" placeholder="已缴合计金额" suffix="元" readonly type="number"
                        :style="{ backgroundColor: '#f5f7fa' }" />
                    <el-button type="text" @click="calculateTotalPaid" size="small">
                        自动计算
                    </el-button>
                </el-form-item>

                <el-divider content-position="left">其他信息</el-divider>

                <el-form-item label="本年度欠缴" prop="currentYearArrears">
                    <el-input v-model.number="feeForm.currentYearArrears" placeholder="本年度欠缴金额" suffix="元" readonly
                        type="number" :style="{ backgroundColor: '#f5f7fa' }" />
                    <el-button type="text" @click="calculateArrears" size="small">
                        自动计算
                    </el-button>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="feeForm.remark" placeholder="请输入备注信息（如缴费提醒、减免说明等）" type="textarea" :rows="3" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="formDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleFormSubmit">
                    确认
                </el-button>
            </template>
        </el-dialog>

        <!-- 删除确认对话框 -->
        <el-dialog v-model="deleteDialogVisible" title="确认删除" width="30%">
            <p>
                您确定要删除 <span class="text-primary">{{ currentFee.enterpriseName }}</span>
                {{ currentFee.feeYear }}年的费用记录吗？此操作不可撤销。
            </p>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete">
                    确认删除
                </el-button>
            </template>
        </el-dialog>

        <!-- 导出设置弹框 -->
        <el-dialog v-model="exportDialogVisible" title="导出设置" width="500px" :close-on-click-modal="false"
            :draggable="true">
            <el-form :model="exportForm" ref="exportFormRef" label-width="100px" class="export-form">
                <!-- 年份选择 -->
                <el-form-item label="选择年份" prop="year"
                    :rules="[{ required: true, message: '请选择年份', trigger: 'change' }]">
                    <!-- <el-date-picker v-model="exportForm.year" type="year" format="YYYY" value-format="YYYY"
                        placeholder="选择年份" class="year-picker" /> -->
                    <el-select v-model="exportForm.year" placeholder="选择年份" clearable @change="handleYear">
                        <el-option v-for="year in searchYears" :key="year" :label="year + '年'" :value="year" />
                    </el-select>

                </el-form-item>

                <!-- 导出格式选择 -->
                <el-form-item label="导出格式" prop="format"
                    :rules="[{ required: true, message: '请选择导出格式', trigger: 'change' }]">
                    <el-select v-model="exportForm.format" placeholder="请选择导出格式" class="format-select">
                        <el-option label="Excel" value="excel" />
                        <el-option label="Word" value="word" />
                        <el-option label="PDF" value="pdf" />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="exportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleExport">确认导出</el-button>
            </template>
        </el-dialog>

        <!-- 导出进度弹框 -->
        <el-dialog v-model="progressDialogVisible" :draggable="true" title="正在导出" width="400px" :show-close="false"
            :close-on-click-modal="false">
            <div class="progress-container">
                <el-progress :percentage="exportProgress" stroke-width="8"
                    :status="exportProgress === 100 ? 'success' : ''" />
                <p class="progress-text">
                    {{ progressMessage }}
                </p>
            </div>
            <template #footer>
                <el-button @click="clearPolling" type="danger">取消导出</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import request from '@/api/request'
import { InfoFilled } from '@element-plus/icons-vue';

// 状态变量
const tableLoading = ref(false);
const detailDialogVisible = ref(false);
const formDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const isEditMode = ref(false);
const currentFee = ref({});
const isMobile = ref(false);

// 搜索表单
const searchForm = reactive({
    enterpriseId: '',
    feeYear: '',
    arrearsStatus: ''
});

// 分页设置
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
});

// 费用表单
const feeForm = reactive({
    feeId: null,
    enterpriseId: '',
    managementFeeUnit: 0,
    propertyFeeUnit: 0,
    payableManagementFee: 0,
    payablePerformanceBond: 0,
    payablePropertyFee: 0,
    payableWaterElectricity: 0,
    policyReduction: 0,
    totalPayable: 0,
    paidManagementFee: 0,
    arrearsManagementFee: 0,
    paidPerformanceBond: 0,
    arrearsPerformanceBond: 0,
    paidPropertyFee: 0,
    arrearsPropertyFee: 0,
    paidWaterElectricity: 0,
    arrearsWaterElectricity: 0,
    totalPaid: 0,
    currentYearArrears: 0,
    feeYear: new Date().getFullYear(),
    remark: ''
});

// 表单验证规则
const formRules = {
    enterpriseId: [
        { required: true, message: '请选择企业', trigger: 'change' }
    ],
    feeYear: [
        { required: true, message: '请选择费用年份', trigger: 'change' }
    ],
    managementFeeUnit: [
        { required: true, message: '请输入管理费单价', trigger: 'blur' },
        { type: 'number', min: 0, message: '管理费单价不能为负数', trigger: 'blur' }
    ],
    propertyFeeUnit: [
        { required: true, message: '请输入物管费单价', trigger: 'blur' },
        { type: 'number', min: 0, message: '物管费单价不能为负数', trigger: 'blur' }
    ],
    payableManagementFee: [
        { required: true, message: '请输入应缴管理费', trigger: 'blur' },
        { type: 'number', min: 0, message: '应缴管理费不能为负数', trigger: 'blur' }
    ],
    payablePerformanceBond: [
        { required: true, message: '请输入应缴履约保证金', trigger: 'blur' },
        { type: 'number', min: 0, message: '应缴履约保证金不能为负数', trigger: 'blur' }
    ],
    payablePropertyFee: [
        { required: true, message: '请输入应缴物管费', trigger: 'blur' },
        { type: 'number', min: 0, message: '应缴物管费不能为负数', trigger: 'blur' }
    ],
    payableWaterElectricity: [
        { required: true, message: '请输入应缴水电费', trigger: 'blur' },
        { type: 'number', min: 0, message: '应缴水电费不能为负数', trigger: 'blur' }
    ],
    policyReduction: [
        { type: 'number', min: 0, message: '政策减免不能为负数', trigger: 'blur' }
    ],
    totalPayable: [
        { required: true, message: '请输入应缴合计', trigger: 'blur' },
        { type: 'number', min: 0, message: '应缴合计不能为负数', trigger: 'blur' }
    ],
    totalPaid: [
        { type: 'number', min: 0, message: '已缴合计不能为负数', trigger: 'blur' }
    ],
    currentYearArrears: [
        { type: 'number', min: 0, message: '本年度欠缴不能为负数', trigger: 'blur' }
    ]
};

// 企业列表,下拉选择
const enterprises = ref([]);

// 可用年份
const availableYears = ref([]);
const searchYears = ref([]);

// 费用列表数据
const feeList = ref([]);


// 对话框宽度
const detailDialogWidth = computed(() => {
    return isMobile.value ? '95%' : '80%';
});

const formDialogWidth = computed(() => {
    return isMobile.value ? '95%' : '60%';
});

// 监听窗口大小，判断是否为移动设备
const handleResize = () => {
    isMobile.value = window.innerWidth < 768;
};

//年份
const yearTotal = ref(null)
//总应缴金额
const myTotalPayable = ref(0)
//总已缴金额
const myTotalPaid = ref(0)
//总欠缴金额
const totalArrears = ref(0)
//政策减免总额
const totalPolicyReduction = ref(0)

// 生命周期钩子
onMounted(() => {
    handleResize();
    window.addEventListener('resize', handleResize);

    //查询统计
    loadStatistics()

    //查询企业
    loadEnterprise()


    //查询年份下拉
    loadsearchFeeYear(null)

    // 加载数据
    loadFeeData();
});

const handleYear = (value) => {
    yearTotal.value = value
    loadStatistics(value)
    loadFeeData();
}

const handleEnterpriseId = (value) => {
    loadFeeData();
}
const handleArrearsStatus = (value) => {
    loadFeeData();
}

const loadStatistics = async (value) => {
    const data = await request.get('enterprise-fee/statistics', {
        params: {
            year: value
        }
    });
    if (data.success) {
        myTotalPayable.value = data.data.total_payable
        myTotalPaid.value = data.data.total_paid
        totalArrears.value = data.data.current_year_arrears
        totalPolicyReduction.value = data.data.policy_reduction
    } else {
        ElMessage.error("请求后端接口失败")
    }
}

//查询企业作为下拉选择
const loadEnterprise = async () => {
    const data = await request.get('enterprise-fee/getEnterprise')
    if (data.success) {
        data.data.map(item => {
            enterprises.value.push({
                id: item.enterpriseId,
                name: item.enterpriseName
            })
        })
    }
}

//查询年份下拉
//传入选中的企业id，查询企业合同开始时间和结束时间，计算返回收费年份信息
const loadFeeYear = async (enterpriseId) => {
    availableYears.value = []
    feeForm.feeYear = null
    const feeYear = await request.get("/enterprise-fee/getFeeYear", {
        params: {
            enterpriseId: enterpriseId
        }
    })
    if (feeYear.success) {
        availableYears.value = feeYear.data
    } else {
        ElMessage.error(feeYear.message)
    }
}
const loadsearchFeeYear = async (enterpriseId) => {
    const feeYear = await request.get("/enterprise-fee/getFeeYear", {
        params: {
            enterpriseId: enterpriseId
        }
    })
    if (feeYear.success) {
        searchYears.value = feeYear.data
    } else {
        ElMessage.error(feeYear.message)
    }
}

// 加载费用数据
const loadFeeData = async () => {
    tableLoading.value = true;
    try {
        const fee = await request.get("enterprise-fee/list", {
            params: {
                enterpriseId: searchForm.enterpriseId,
                feeYear: searchForm.feeYear,
                arrearsStatus: searchForm.arrearsStatus,
                pageNum: pagination.currentPage,
                pageSize: pagination.pageSize
            }
        })
        if (fee.success) {
            feeList.value = fee.data.list
            pagination.total = fee.data.total

        }
    } catch (error) {
        ElMessage.error('加载费用数据失败: ' + (error.message || '未知错误'));
    } finally {
        tableLoading.value = false;
    }
};

// 查看详情
const handleViewDetail = (row) => {
    currentFee.value = { ...row };
    detailDialogVisible.value = true;
};

// 行点击事件
const handleRowClick = (row) => {
    // 在移动设备上点击行直接查看详情
    if (isMobile.value) {
        handleViewDetail(row);
    }
};

// 新增费用记录
const handleAdd = () => {
    feeFormRef.value?.resetFields();
    enterpriseTooltip.value = "信息加载中..."
    isEditMode.value = false;
    // 重置表单
    Object.keys(feeForm).forEach(key => {
        if (key === 'feeYear') {
            feeForm[key] = new Date().getFullYear();
        } else if (key !== 'feeId') {
            feeForm[key] = key.includes('Fee') || key.includes('Reduction') || key.includes('Arrears') ? 0 : '';
        }
    });
    availableYears.value = []
    feeForm.feeYear = null
    formDialogVisible.value = true;
};

// 编辑费用记录
const handleEdit = (row) => {
    feeFormRef.value?.resetFields();
    enterpriseTooltip.value = "信息加载中..."
    isEditMode.value = true;
    availableYears.value = []
    feeForm.feeYear = null
    // 填充表单数据
    Object.keys(feeForm).forEach(key => {
        feeForm[key] = row[key] !== undefined ? row[key] : (key.includes('Fee') || key.includes('Reduction') || key.includes('Arrears') ? 0 : '');
    });
    formDialogVisible.value = true;
    getEnterpriseInfo(row.enterpriseId)
};



const enterpriseTooltip = ref('信息加载中...'); // 企业提示
const propertyArea = ref(0)
const useArea = ref(0)

//新增编辑弹框中选中企业后，查询显示企业所在园区、位置、楼栋、楼层、房间信息
const handleEnterPriseChange = (enterpriseId) => {
    try {
        if (enterpriseId) {
            loadFeeYear(enterpriseId)
            getEnterpriseInfo(enterpriseId)
        }
    } catch (err) {

    }
}
const getEnterpriseInfo = (enterpriseId) => {
    request.get('enterprise-fee/relations/' + enterpriseId).then(res => {
        if (res.success) {
            const data = res.data
            const parkName = data.parkInfo.name
            const parkBuildingName = data.parkBuilding.name
            const room = data.enterpriseRoomPojos.map(item => {
                return item.parkRoom.floor + "层" + item.parkRoom.roomNumber + "号"
            })

            propertyArea.value = data.enterpriseRoomPojos
                .map(item => Number(item.enterprisePropertyArea) || 0)
                .reduce((total, current) => total + current, 0).toFixed(2);

            // 计算总面积
            useArea.value = data.enterpriseRoomPojos
                .map(item => Number(item.enterpriseUseArea) || 0)
                .reduce((total, current) => total + current, 0).toFixed(2);

            enterpriseTooltip.value = "<div>园区：" + parkName + "</div>" +
                "<div>楼栋：" + parkBuildingName + "</div><div>楼层/房间：" + room + "</div><div>使用面积：" + useArea.value +
                "㎡；</div><div>物业面积：" + propertyArea.value + "㎡"


            if (feeForm.managementFeeUnit) {
                feeForm.payableManagementFee = Number(useArea.value) * Number(feeForm.managementFeeUnit) * 12
            }
            if (feeForm.propertyFeeUnit) {
                feeForm.payablePropertyFee = Number(propertyArea.value) * Number(feeForm.propertyFeeUnit) * 12
            }
        } else {
            enterpriseTooltip.value = res.message
            availableYears.value = []
            feeForm.feeYear = null
            useArea.value = 0
            propertyArea.value = 0
        }

    })
}
//管理费输入监听，输入后自动计算应缴管理费
const handleInputManagementFeeUnit = (value) => {
    console.log(feeForm, "feeForm")
    console.log(feeForm.enterpriseId, "feeForm.enterpriseId")
    if (feeForm.enterpriseId) {
        //如果已经选择了企业则计算
        feeForm.payableManagementFee = Number(useArea.value) * Number(value) * 12
    }
    console.log(feeForm.payableManagementFee, "feeForm.payableManagementFee")
}

//物管费单价输入监听，输入后自动计算应缴物理费
const handleInputPropertyFeeUnit = (value) => {
    if (feeForm.enterpriseId) {
        //如果已经选择了企业则计算
        feeForm.payablePropertyFee = Number(propertyArea.value) * Number(value) * 12
    }
}


//新增编辑清除选中企业后
const handleEnterPriseClear = () => {
    feeForm.payableManagementFee = 0
    feeForm.payablePropertyFee = 0
    availableYears.value = []
    feeForm.feeYear = null
}


// 删除费用记录
const handleDelete = (row) => {
    currentFee.value = { ...row };
    deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
    try {
        const remove = await request.get("enterprise-fee/remove/" + currentFee.value.feeId)
        if (remove.success) {
            ElMessage.success(remove.message);
            deleteDialogVisible.value = false;
            loadFeeData()
            loadStatistics()
        }
        else {
            ElMessage.error(remove.message);
        }
    } catch (error) {
        ElMessage.error('删除失败: ' + (error.message || '未知错误'));
    }
};

// 表单提交
const feeFormRef = ref(null);
const handleFormSubmit = async () => {
    try {
        // 表单验证
        await feeFormRef.value.validate();

        // 计算欠缴金额
        calculateTotalPaid();
        calculateArrears();
        calculateTotalPayable();

        let url = "enterprise-fee/add"

        if (isEditMode.value) {
            url = "enterprise-fee/modify"
        } else {
        }

        const res = await request.post(url, feeForm)
        if (res.success) {
            formDialogVisible.value = false;
            ElMessage.success(res.message);
            loadFeeData()
            loadStatistics()
        } else {
            ElMessage.error(res.message);
        }
    } catch (error) {
        console.log(error, "表单提交错误")
        if (error.name !== 'ValidationError') {
            ElMessage.error('操作失败: ' + (error.message || '表单验证错误'));
        }
    }
};

// 计算应缴合计计算公式：应缴管理费+应缴履约保证金+应缴物管费+应缴水电-政策减免/年
const calculateTotalPayable = () => {
    feeForm.totalPayable = (
        Number(feeForm.payableManagementFee) +
        Number(feeForm.payablePerformanceBond) +
        Number(feeForm.payablePropertyFee) +
        Number(feeForm.payableWaterElectricity) -
        Number(feeForm.policyReduction)
    ).toFixed(2) * 1;
};

// 计算已缴合计
const calculateTotalPaid = () => {
    feeForm.totalPaid = (
        Number(feeForm.paidManagementFee) +
        Number(feeForm.paidPerformanceBond) +
        Number(feeForm.paidPropertyFee) +
        Number(feeForm.paidWaterElectricity)
    ).toFixed(2) * 1;
};

// 计算欠缴金额
const calculateArrears = () => {
    // 计算各项欠缴
    feeForm.arrearsManagementFee = (Number(feeForm.payableManagementFee) - Number(feeForm.paidManagementFee)).toFixed(2) * 1;
    feeForm.arrearsPerformanceBond = (Number(feeForm.payablePerformanceBond) - Number(feeForm.paidPerformanceBond)).toFixed(2) * 1;
    feeForm.arrearsPropertyFee = (Number(feeForm.payablePropertyFee) - Number(feeForm.paidPropertyFee)).toFixed(2) * 1;
    feeForm.arrearsWaterElectricity = (Number(feeForm.payableWaterElectricity) - Number(feeForm.paidWaterElectricity)).toFixed(2) * 1;

    // 计算本年度欠缴总额
    feeForm.currentYearArrears = (
        feeForm.arrearsManagementFee +
        feeForm.arrearsPerformanceBond +
        feeForm.arrearsPropertyFee +
        feeForm.arrearsWaterElectricity - feeForm.policyReduction
    ).toFixed(2) * 1;
};

// 重置搜索表单
const handleSearch = () => {
    loadFeeData()
};
const handleReset = () => {
    searchForm.enterpriseId = '';
    searchForm.feeYear = '';
    searchForm.arrearsStatus = '';
    pagination.currentPage = 1;
    loadFeeData()
};


// 分页事件处理
const handlePageSizeChange = (size) => {
    pagination.pageSize = size;
    loadFeeData()
};

const handleCurrentPageChange = (page) => {
    pagination.currentPage = page;
    loadFeeData()
};

// 格式化货币
const formatCurrency = (amount) => {
    if (amount === null || amount === undefined) return '0.00';

    // 转换为数字并保留两位小数
    const num = Number(amount).toFixed(2);

    // 添加千位分隔符
    return num.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

/**
 * 导出功能区
 */
// 导出设置弹框状态
const exportDialogVisible = ref(false);
// 进度弹框状态
const progressDialogVisible = ref(false);
// 导出进度
const exportProgress = ref(0);
// 进度信息
const progressMessage = ref('准备导出数据...');

const taskId = ref(null);
const exportStatus = ref(''); // waiting/processing/completed/failed
const progressTimer = ref(null);

// 导出表单数据
const exportForm = reactive({
    year: '',
    format: ''
});

// 表单引用
const exportFormRef = ref(null);

// 打开导出弹框
const openExportDialog = () => {
    exportDialogVisible.value = true;
    // 重置表单
    exportForm.year = '';
    exportForm.format = '';
    if (exportFormRef.value) {
        exportFormRef.value.resetFields();
    }
};

// 处理导出
const handleExport = async () => {
    // 表单验证
    const valid = await exportFormRef.value.validate();
    if (!valid) return;

    progressDialogVisible.value = true;
    exportProgress.value = 0;
    progressMessage.value = '正在准备导出数据...';
    simulateExportProcess();
};

// 导出进度
const simulateExportProcess = async () => {

    const exportParams = {
        keyword: exportForm.year, // 前端查询条件
        fileName: exportForm.year + "年缴费情况统计表", // 自定义文件名
    };
    try {
        const res = await request.post('/export/create-task', exportParams, {
            params: { exportType: exportForm.format } // 导出类型
        });
        if (res.success) {
            taskId.value = res.data;
            exportStatus.value = 'WAITING';
            startPolling(); // 启动轮询
            progressMessage.value = '导出任务已启动，正在处理中...';
        } else {
            progressDialogVisible.value = false;
            ElMessage.error(`创建导出任务失败：${res.message || res.message}`);
        }
    } catch (err) {
        progressDialogVisible.value = false;
        progressDialogVisible.value = false;
        ElMessage.error(`创建导出任务失败：${err.response?.data?.msg || err.message}`);
    }
};

// 2. 启动轮询（查询进度）
const startPolling = () => {
    // 清除旧定时器（避免重复）
    if (progressTimer.value) {
        clearInterval(progressTimer.value);
    }

    // 初始立即查询一次，再开始轮询
    queryTaskStatus();

    // 每秒轮询一次
    progressTimer.value = setInterval(() => {
        queryTaskStatus();
    }, 1000);
};
// 查询任务状态
const queryTaskStatus = async () => {
    if (!taskId.value) return;

    try {
        const res = await request.get('/export/task-status', {
            params: { taskId: taskId.value }
        });

        const task = res.data;
        exportProgress.value = task.progress;
        exportStatus.value = task.status;

        // 根据状态处理
        if (task.status === 'COMPLETED') {
            clearPolling();
            downloadFile(); // 导出完成，触发下载
            progressMessage.value = '导出完成，开始下载';
        } else if (task.status === 'FAILED') {
            clearPolling();
            progressDialogVisible.value = false;
            ElMessage.error(`导出失败：${task.errorMsg || '未知错误'}`);
        }
    } catch (err) {
        clearPolling();
        progressDialogVisible.value = false;
        ElMessage.error(`查询导出进度失败：${err.response?.data?.msg || err.message}`);
    }
};
// 3. 下载文件
const downloadFile = () => {
    if (!taskId.value) return;

    try {
        const url = import.meta.env.VITE_BASE_API + `export/download?taskId=${taskId.value}`;
        const a = document.createElement('a');
        a.href = url;
        a.style.display = 'none';
        // 设置下载文件名（可选，后端也可以设置）
        // a.download = '用户列表.xlsx';
        document.body.appendChild(a);
        a.click();
        // 延迟移除a标签，确保下载请求完成
        setTimeout(() => {
            document.body.removeChild(a);
            progressDialogVisible.value = false;
        }, 100);
    } catch (err) {
        progressDialogVisible.value = false;
        ElMessage.error(`文件下载失败：${err.message}`);
    }
};

// 4. 清除定时器
const clearPolling = () => {
    if (progressTimer.value) {
        clearInterval(progressTimer.value);
        progressTimer.value = null;
    }
    progressDialogVisible.value = false;
};

</script>

<style scoped>
.enterprise-fee-management {
    background-color: #f5f7fa;
}

.stats-card-row {
    margin-top: 10px;
    margin-bottom: 20px;
}

.stats-card {
    height: 100%;
    transition: all 0.3s ease;
}

.stats-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stats-card-content {
    padding: 15px 0;
}

.search-form {
    text-align: left;
}

:depp(.el-form--inline .el-form-item) {
    margin-right: 15px;
}

.stats-card-label {
    color: #606266;
    font-size: 14px;
    margin-bottom: 10px;
}

.stats-card-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
    color: #303133;
}

.stats-card-desc {
    font-size: 12px;
    color: #909399;
}

.pagination-container {
    margin-top: 15px;
    text-align: right;
}

.fee-form {
    max-height: 65vh;
    overflow-y: auto;
    padding-right: 10px;
}

.font-bold {
    font-weight: bold;
}

/* 提示图标列样式 */
.tooltip-col {
    display: flex;
    align-items: center;
    justify-content: center;
    /* 调整图标与输入框的垂直对齐 */
    margin-top: -15px;
}

/* 提示图标样式 */
.question-icon {
    color: #606266;
    cursor: help;
    transition: color 0.2s;
}

.question-icon:hover {
    color: #409eff;
    /* Element Plus 主题色 */
}

.select-with-tooltip {
    display: flex;
    align-items: center;
    gap: 8px;
    /* 调整选择器和图标之间的间距 */
}

.info-icon {
    color: #606266;
    /* 图标颜色，与表单元素保持一致 */
    cursor: help;
    /* 鼠标悬停时显示帮助指针 */
    font-size: 16px;
}
</style>